package com.shengde.jinwawaforleader.model.personalCenter.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.myJob.instance_message.Constant;
import com.shengde.jinwawaforleader.model.myJob.instance_message.ObserveBigPicActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadData;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.network.protocolbean.ProUserInfo;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.views.CircleImageView;
import com.shengde.jinwawaforleader.views.SelectPicPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/9/14 0014.
 */
public class PersonalInfoActivity extends BaseActivity implements LGImgCompressor.CompressListener {
	private static final String TAG = "PersonalInfoActivity";
	private static final int TAKE_PICTURE = 1;
	private static final int SELECT_PICTURE = 2;
	private static final int FINSH = 3;

	private TextView tv_back;
	private TextView tv_title;
	private TextView fill_add;//保存
	private TextView tv_name;//姓名
	private TextView tv_sexy;//性别
	private TextView tv_person_name;//个性签名
	String mEdtStringName;  //回调后显示的名字
	String mEdtStringPersonalSign; //回调后显示的个性签名
	String mEdtStringPersonalSexy; //回调后显示的性别 0 :1
	String mLogo;
	String mName;
	String mGender;
	String mMemo;
	private RelativeLayout relative_iv_baby_name;//姓名条目
	private RelativeLayout relative_iv_baby_sexy; //性别条目
	private RelativeLayout relative_iv_baby_person_name; //个性签名条目
	private CircleImageView riv_add_logo;  //更换头像
	SelectPicPopupWindow showPopupWindow; //自定义popuowindow

	private String path = "";
	private String mUrl;
	private String picName;  //拍摄图片的名字

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case FINSH:
					showUploadData(mUrl, mEdtStringName, mEdtStringPersonalSign, judgeSexy(mEdtStringPersonalSexy));
					break;
			}
		}
	};


	@Override
	public void onRoot(Bundle savedInstanceState) {
		setContentView(R.layout.person_info_activity);
	}

	@Override
	public void initView() {

		tv_back = (TextView) findViewById(R.id.tv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		fill_add = (TextView) findViewById(R.id.fill_add);

		riv_add_logo = (CircleImageView) findViewById(R.id.riv_add_logo);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_sexy = (TextView) findViewById(R.id.tv_sexy);
		tv_person_name = (TextView) findViewById(R.id.tv_person_name);
		relative_iv_baby_name = (RelativeLayout) findViewById(R.id.relative_iv_baby_name);

		relative_iv_baby_sexy = (RelativeLayout) findViewById(R.id.relative_iv_baby_sexy);
		relative_iv_baby_person_name = (RelativeLayout) findViewById(R.id.relative_iv_baby_person_name);
	}

	@Override
	public void initData() {
		tv_title.setText(getString(R.string.personal_information));
		fill_add.setText(getString(R.string.save));
		showUserInfo();

	}

	@Override
	public void initListener() {
		tv_back.setOnClickListener(this);
		riv_add_logo.setOnClickListener(this);
		fill_add.setOnClickListener(this);
		relative_iv_baby_name.setOnClickListener(this);
		relative_iv_baby_sexy.setOnClickListener(this);
		relative_iv_baby_person_name.setOnClickListener(this);
	}

	@Override
	public void onWidgetClick(View view) {
		switch (view.getId()) {
			case R.id.tv_back:
				finish();
				break;
			case R.id.riv_add_logo:
				showPopupWindow(view);
				break;
			case R.id.fill_add:
				if ("".equals(path)) {
					showUploadData(mLogo, mEdtStringName, mEdtStringPersonalSign, judgeSexy(mEdtStringPersonalSexy));
				} else {
					compressImage();
				}
				break;
			case R.id.relative_iv_baby_name:
				Intent intent = new Intent(this, EditBabyNameActivity.class);
				intent.putExtra("relative_iv_baby", "1");
				startActivityForResult(intent, Constant.REQUEST_CODE);
				break;
			case R.id.relative_iv_baby_sexy:
				intent = new Intent(this, EditBabySexyActivity.class);
				intent.putExtra("select_radio", "1");
				startActivityForResult(intent, Constant.REQUEST_CODE_SEXY);
				break;
			case R.id.relative_iv_baby_person_name:
				intent = new Intent(this, EditBabyNameActivity.class);
				intent.putExtra("relative_iv_baby", "2");
				startActivityForResult(intent, Constant.REQUEST_CODE);
				break;
		}
	}

	/**
	 * 判断 性别 男 还是女
	 * @param mEdtStringPersonalSexy
	 * @return
	 */
	private String judgeSexy(String mEdtStringPersonalSexy) {
		if ("男".equals(mEdtStringPersonalSexy)) {
			mEdtStringPersonalSexy = "1";
		} else if ("女".equals(mEdtStringPersonalSexy)) {
			mEdtStringPersonalSexy = "0";
		}
		return mEdtStringPersonalSexy;
	}

	/**
	 * 压缩图片
	 */
	private void compressImage() {
		LGImgCompressor.getInstance(PersonalInfoActivity.this).withListener(PersonalInfoActivity.this).
				starCompress(Uri.fromFile(new File(path)).toString(), 600, 800, 100);

	}

	//显示 弹窗
	private void showPopupWindow(View v) {

		showPopupWindow = new SelectPicPopupWindow(this, itemsOnClick);
		showPopupWindow.tv_video_babydiary_share.setText(getString(R.string.take_photo));
		showPopupWindow.tv_video_babydiary_share.setTextColor(Color.parseColor("#067DFF"));
		showPopupWindow.tv_video_babydiary_delete.setTextColor(Color.parseColor("#067DFF"));
		showPopupWindow.tv_look_big_pic.setText(getString(R.string.look_big_pic));
		showPopupWindow.tv_look_big_pic.setTextColor(Color.parseColor("#067DFF"));
		showPopupWindow.tv_video_babydiary_delete.setText(getString(R.string.get_phone_picture));
		showPopupWindow.tv_video_babydiary_cancle.setTextColor(Color.parseColor("#067DFF"));

		//设置layout在PopupWindow中显示的位置
		showPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	//为弹出窗口实现监听类
	private View.OnClickListener itemsOnClick = new View.OnClickListener() {

		public void onClick(View v) {
			showPopupWindow.dismiss();
			switch (v.getId()) {
				case R.id.tv_video_babydiary_share:  //拍摄
					//先验证手机是否有sdcard
					String status = Environment.getExternalStorageState();
					if (status.equals(Environment.MEDIA_MOUNTED)) {
						try {
							File dir = new File(Environment.getExternalStorageDirectory() + "/sdcard/cache/");
							if (!dir.exists()) {
								dir.mkdirs();
							}
							Intent intent = new Intent();
							intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
							picName = new Date().getTime() + ".jpg";
							Uri uri = Uri.fromFile(new File(dir, picName));
							intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
							intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
							startActivityForResult(intent, TAKE_PICTURE);
						} catch (ActivityNotFoundException e) {
							Toast.makeText(PersonalInfoActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
						}
					}
					showPopupWindow.dismiss();

					break;
				case R.id.tv_video_babydiary_delete: //手机中获取
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_PICK);
					intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
					startActivityForResult(intent, SELECT_PICTURE);
					showPopupWindow.dismiss();
					break;
				case R.id.tv_video_babydiary_cancle:
					showPopupWindow.dismiss();
					break;
				case R.id.tv_look_big_pic:
					intent = new Intent(PersonalInfoActivity.this, ObserveBigPicActivity.class);
					if ("".equals(path)) {
						intent.putExtra("big_img_url", BaseProtocol.IMG_BASE + mLogo);
					} else {
						intent.putExtra("big_img_url", path);
					}
					startActivity(intent);
					break;
			}
		}
	};

	/**
	 * 上传图片
	 *
	 * @param path 压缩后图片的路径
	 */
	private void showUploadPic(String path) {

		String url = BaseProtocol.IMG_UPLOAD_HOST;
		RequestParams params = BaseProtocol.getRequestParams(url);
		params.addHeader("User-Agent", "SOHUWapRebot");
		params.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
		params.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
		params.addHeader("Connection", "keep-alive");
		params.setMultipart(true);
		params.addBodyParameter("pic", new File(path));
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProUploadImg pro_class_status = new Gson().fromJson(result, ProUploadImg.class);
				Log.i(TAG, "onSuccess: code" + pro_class_status.getCode());
				if (pro_class_status != null && pro_class_status.getCode() == 0) {
					List<String> mUrlList = pro_class_status.getUrl();
					if (mUrlList.size() > 0) {
						mUrl = mUrlList.get(0);
						Log.i(TAG, "onSuccess: mUrl" + mUrl);
					}
					mHandler.sendEmptyMessage(FINSH);

				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.i(TAG, "onError: ex = " + ex);
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});

	}

	/**
	 * 二次上传 数据
	 *
	 * @param mUrl
	 * @param mEdtStringName
	 * @param mEdtStringPersonalSign
	 * @param mEdtStringPersonalSexy
	 */
	private void showUploadData(String mUrl, String mEdtStringName, String mEdtStringPersonalSign, String mEdtStringPersonalSexy) {
		String url = "";
		if (User.isTest) {
			url = BaseProtocol.HOST_BASE_TEST + "/parent/UserLogoUpdate";
		} else {
			url = BaseProtocol.HOST_BASE + "/parent/UserLogoUpdate";
		}
		RequestParams params = BaseProtocol.getRequestParams(url);
		params.addParameter("userid", User.getUserLoginAccount(this));
		params.addParameter("newlogo", mUrl);
		params.addParameter("name", mEdtStringName);
		params.addParameter("gender", mEdtStringPersonalSexy);
		params.addParameter("memo", mEdtStringPersonalSign);
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProUploadData pro_class_status = new Gson().fromJson(result, ProUploadData.class);
				if (pro_class_status != null && pro_class_status.getCode() == 0) {
					Toast.makeText(PersonalInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
					setResult(Constant.SETTING_LOGO);
					finish();
				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.i(TAG, "onError: ex" + ex);
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});
	}

	/**
	 * 获取用户头像
	 */
	private void showUserInfo() {
		String url = "";
		if (User.isTest) {
			url = BaseProtocol.HOST_BASE_TEST + "/parent/UserLogo";
		} else {
			url = BaseProtocol.HOST_BASE + "/parent/UserLogo";
		}
		RequestParams params = BaseProtocol.getRequestParams(url);
		params.addParameter("userid", User.getUserLoginAccount(this));
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProUserInfo pro_class_status = new Gson().fromJson(result, ProUserInfo.class);
				if (pro_class_status != null && pro_class_status.getCode() == 0) {
					mLogo = pro_class_status.getLogo();
					mName = pro_class_status.getName();

					mGender = pro_class_status.getGender();
					mMemo = pro_class_status.getMemo();
					if ("1".equals(mGender)) {
						tv_sexy.setText(getString(R.string.man));
					} else if ("0".equals(mGender)) {
						tv_sexy.setText(getString(R.string.woman));
					}
					Glide.with(PersonalInfoActivity.this).load(BaseProtocol.IMG_BASE + mLogo)
							.error(R.drawable.touxiang)
							.into(riv_add_logo);
					tv_name.setText(mName);
					tv_person_name.setText(mMemo);
				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {

			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SELECT_PICTURE) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri uriPath = data.getData();

					if (!"".equals(uriPath.getAuthority())) {
						Cursor cursor = getContentResolver().query(uriPath,
								new String[]{MediaStore.Images.Media.DATA},
								null, null, null);
						cursor.moveToFirst();
						path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
					} else {
						path = uriPath.getPath();
					}
					mLogo = path;
					Glide.with(this).load(path).into(riv_add_logo);

				}
			}
		} else if (requestCode == TAKE_PICTURE) {
			if (resultCode == RESULT_OK) {

				String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sdcard/cache/" + picName;

				Bitmap bm = BitmapFactory.decodeFile(filePath);

				final File myCaptureFile = new File(filePath);
				try {
					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(myCaptureFile));
					/* 采用压缩转档方法 */
					bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
					/* 调用flush()方法，更新BufferStream */
					bos.flush();
					/* 结束OutputStream */
					bos.close();
					path = myCaptureFile.getAbsolutePath();
					mLogo = path;

					Glide.with(this).load(path).into(riv_add_logo);

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if (requestCode == Constant.REQUEST_CODE) {
			if (resultCode == Constant.SETTING_PERSON_NAME_SAVE_SUCCESS) {


				mEdtStringName = data.getExtras().getString("name");
				tv_name.setText(mEdtStringName);

			} else if (resultCode == Constant.SETTING_PERSONAL_SIGN_SAVE_SUCCESS) {
				mEdtStringPersonalSign = data.getExtras().getString("personal_sign");
				tv_person_name.setText(mEdtStringPersonalSign);

			}
		}
		if (requestCode == Constant.REQUEST_CODE_SEXY && resultCode == Constant.SETTING_SEXY_SAVE_SUCCESS) {
			mEdtStringPersonalSexy = data.getExtras().getString("mSexy");
			tv_sexy.setText(mEdtStringPersonalSexy);
		}
	}

	@Override
	public void onCompressStart() {
		Log.d(TAG, "onCompressStart");
	}

	@Override
	public void onCompressEnd(LGImgCompressor.CompressResult compressResult) {
		Log.d(TAG, "onCompressEnd outPath:" + compressResult.getOutPath());
		if (compressResult.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
			return;

		File file = new File(compressResult.getOutPath());
		Bitmap bitmap = null;
		try {
			bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
			float imageFileSize = file.length() / 1024f;
			Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
					" \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
			path = file.getAbsolutePath();
			Log.i(TAG, "onCompressEnd: imagePath_one = " + file.getAbsolutePath());
			Log.i(TAG, "onCompressEnd: imagePath_two = " + compressResult.getOutPath());
			showUploadPic(path);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
